//
//  LoginViewController.m
//  跨界收
//
//  Created by MT on 2018/10/27.
//  Copyright © 2018年 gztx. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "TabBarController.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneTf;
@property (weak, nonatomic) IBOutlet UITextField *codeTf;
@property (weak, nonatomic) IBOutlet UIButton *checkBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property(nonatomic,assign)int setAliasCount;
@property(nonatomic,copy)NSString *alias;
@end

@implementation LoginViewController

- (void)dealloc {
    [self removeObservers];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self initConfigure];
    
    [self buildInterface];
}

- (void)initConfigure {
    self.title = @"登录";
    
    [self addObservers];
}
- (void)buildInterface {
    
}


#pragma mark -- private methods
- (void)addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getsmsAction)
                                                 name:kRegisterViewControllerNeedFetchCodeNotificationKey
                                               object:nil];
}
- (void)removeObservers {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kRegisterViewControllerNeedFetchCodeNotificationKey
                                                  object:nil];
}


#pragma mark - Event -
//获取验证码
- (IBAction)getCode:(UIButton *)sender {
    if (![Tool IsPhoneNumber:self.phoneTf.text]){
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    //验证码倒计时
    __block int timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(timer, ^{
        if(timeout == 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(),
                           ^{
                               sender.userInteractionEnabled = YES;
                               [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                           });
        } else {
            int seconds = timeout % 61;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                NSString *title = [NSString stringWithFormat:@"(%@s)",strTime];
                [sender setTitle:title forState:UIControlStateNormal];
                sender.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(timer);
    
    [self getsmsAction];
}

- (IBAction)login:(UIButton *)sender {
    if (![Tool IsPhoneNumber:self.phoneTf.text]){
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    
    if (self.codeTf.text.length == 0 || self.codeTf.text == nil){
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    
    if (!self.codeBtn.selected) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"请阅读并同意%@协议",appName]];
        return;
    }
    
    //登录请求
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"account"] = self.phoneTf.text;
    dic[@"code"] = self.codeTf.text;
    dic[@"sn"] = [Tool currentTimeStr];
    dic[@"pv"] = @"ios";
    dic[@"v"] = AppVersion;
    
    NSString *sign = [Tool sortSign:dic];
    dic[@"sign"] = sign;
    NSLog(@"%@",sign);
    if ([Tool getLocalDataValue:@"serverUrl"] == nil) {
        [[AppStartRequestObject instance] getAPIRequest];
    }else{
        [self loginRequest:dic];
    }
}

- (IBAction)selecCheck:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (IBAction)gotoRegister:(UIButton *)sender {
    RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:registerVC];
    [self presentViewController:navi animated:YES completion:nil];
}

#pragma mark - request -
//获取验证码请求
- (void)getsmsAction {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"mobile"] = self.phoneTf.text;
    dic[@"type"] = @1;
    dic[@"sn"] = [Tool currentTimeStr];
    dic[@"pv"] = @"ios";
    dic[@"v"] = AppVersion;
    
    NSString *sign = [Tool sortSign:dic];
    dic[@"sign"] = sign;
    NSLog(@"%@",sign);
    if ([Tool getLocalDataValue:@"serverUrl"] == nil) {        
        [[AppStartRequestObject instance] getAPIRequest];
    }else{
        [self getsmsRequest:dic];
    }
}

- (void)getsmsRequest:(NSDictionary *)dic {
    [NetworkManager post:[NetworkHelper accountCodeURL] parameters:dic success:^(id object) {
        
        if ([object[@"status"] intValue] == 1) {
            [SVProgressHUD showSuccessWithStatus:@"短信下发成功"];
        }else{
            [SVProgressHUD showSuccessWithStatus:@"短信下发失败"];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络出现异常，请检查您的网络状态"];
    }];
}

- (void)loginRequest:(NSDictionary *)dic{
    [NetworkManager post:[NetworkHelper loginURL] parameters:dic success:^(id object) {
        
        if ([object[@"status"] intValue] == 1) {
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            
            [Tool setLocalDataValue:object[@"data"][@"token"] key:@"X-Access-Token"];
            
            NSString *urlStr = object[@"data"][@"url"];
            
            if ([urlStr containsString:@"?"]) {
                urlStr = [NSString stringWithFormat:@"%@&token=%@",urlStr,[Tool getLocalDataValue:@"X-Access-Token"]];
            }else{
                urlStr = [NSString stringWithFormat:@"%@?&token=%@",urlStr,[Tool getLocalDataValue:@"X-Access-Token"]];
            }
        
            [self getUserInfoRequest];
            
            int64_t delayInSeconds = 1.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // 跳转
                TabBarController *tabBarController = [[TabBarController alloc] init];
                
                [UIApplication sharedApplication].keyWindow.rootViewController = [[UINavigationController alloc]initWithRootViewController:tabBarController];;
            });
        }else{
            [SVProgressHUD showErrorWithStatus:@"msg"];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络出现异常，请检查您的网络状态"];
    }];
}

//获取用户信息
- (void)getUserInfoRequest{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = [Tool getLocalDataValue:@"token"];
    dic[@"type"] = @1;
    dic[@"sn"] = [Tool currentTimeStr];
    dic[@"pv"] = @"ios";
    dic[@"v"] = AppVersion;
    
    NSString *sign = [Tool sortSign:dic];
    dic[@"sign"] = sign;
    NSLog(@"%@",sign);
    [NetworkManager post:URLSPL([Tool getLocalDataValue:@"serverUrl"], getUserInfo) parameters:dic success:^(id object) {
        if ([object[@"status"] intValue] == 1) {
            
            [Tool setLocalDataDictionary:object[@"data"] key:@"UserInfo"];
            
            NSString *urlStr = object[@"data"][@"url"];
            
            if ([urlStr containsString:@"?"]) {
                urlStr = [NSString stringWithFormat:@"%@&token=%@",urlStr,[Tool getLocalDataValue:@"token"]];
            }else{
                urlStr = [NSString stringWithFormat:@"%@?&token=%@",urlStr,[Tool getLocalDataValue:@"token"]];
            }
            
            self.setAliasCount = 0;
            
            self.alias = object[@"data"][@"jg_alias"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //        if ([Tool getLocalDataValue:@"jg_alia"]) {
                [JPUSHService setAlias:self.alias callbackSelector:@selector(aliasCallBack:tag:andAlias:) object:self];
                //        }
                
                // 绑定别名
                [GeTuiSdk bindAlias:self.alias andSequenceNum:kGtAppName];
                
                self.setAliasCount++;
            });
        }
    } failure:^(NSError *error) {
    }];
}

- (void)aliasCallBack:(int)iscall tag:(NSSet*)tags andAlias:(NSString*)alias
{
    NSLog(@"iscode%d--alias=%@--tags=%@",iscall,alias,tags);
    
    if (iscall != 0 && self.setAliasCount <= 3) {
        [JPUSHService setAlias:self.alias callbackSelector:@selector(aliasCallBack:tag:andAlias:) object:self];
    }
}


@end
